<?php

namespace app\store\model\dealer;

use app\common\model\dealer\User as UserModel;
use app\common\model\dealer\Referee as RefereeModel;
/**
 * 分销商用户模型
 * Class User
 * @package app\store\model\dealer
 */
class User extends UserModel
{
    /**
     * 获取分销商用户列表
     * @param string $search
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($search = '')
    {
        // 构建查询规则
        $this->alias('dealer')
            ->field('dealer.*, user.nickName, user.avatarUrl')
            ->with(['referee'])
            ->join('user', 'user.user_id = dealer.user_id')
            ->where('dealer.is_delete', '=', 0)
            ->order(['dealer.create_time' => 'desc']);
        // 查询条件
        !empty($search) && $this->where('user.nickName|dealer.real_name|dealer.mobile', 'like', "%$search%");
        // 获取列表数据
        return $this->paginate(15, false, [
            'query' => \request()->request()
        ]);
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 离职
     * @return false|int
     */
    public function setLeave($dealer_id)
    {
        $dealerModel = self::detail($dealer_id);
        // 清空关系表
        $refereeIds = RefereeModel::where('dealer_id', '=', $dealer_id)->column('id');
        $refereeIds && RefereeModel::deleteAll(['id' => ['in', $refereeIds]]);
        return $dealerModel->save([
            'is_delete' => 1,
            'first_num' => 0,
            'second_num' => 0,
            'third_num' => 0,
            'order_num' => 0,
        ]);
    }

    /**
     * 提现打款成功：累积提现佣金
     * @param $user_id
     * @param $money
     * @return false|int
     * @throws \think\exception\DbException
     */
    public static function totalMoney($user_id, $money)
    {
        $model = self::detail($user_id);
        return $model->save([
            'freeze_money' => $model['freeze_money'] - $money,
            'total_money' => $model['total_money'] + $money,
        ]);
    }

    /**
     * 提现驳回：解冻分销商资金
     * @param $user_id
     * @param $money
     * @return false|int
     * @throws \think\exception\DbException
     */
    public static function backFreezeMoney($user_id, $money)
    {
        $model = self::detail($user_id);
        return $model->save([
            'money' => $model['money'] + $money,
            'freeze_money' => $model['freeze_money'] - $money,
        ]);
    }


    /**
     * 添加分销用户
     * @param $data
     * @return bool
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function addUser($data)
    {
        if(!isset($data['user_id']) or !$data['user_id'])
        {
            $this->error='请选择用户后提交';
            return false;
        }

        //分销用户信息
        $dealer = self::detail($data['user_id']);

        //已存在
        if($this->isDealerUser($data['user_id'])) {
            $this->error='用户已存在';
            return false;
        }
        // 更新记录
        $this->startTrans();
        try {
            // 新增分销商用户记录
            User::add($data['user_id'], [
                'real_name' => $data['real_name'],
                'mobile' => $data['mobile'],
                'remark'=>$data['remark'],
                'referee_id' => RefereeModel::getRefereeUserId($data['user_id'], 1)
            ]);

            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }

    }

    /**
     * 转移关系
     * @param $data
     * @param $dealer_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function dealerLeave($data, $dealer_id)
    {
        if(!isset($data['user_id']) or !$data['user_id']) {
            $this->error = '请选择用户后提交';
            return false;
        }
        if ($dealer_id == $data['user_id']) {
            $this->error = "无法转移给自己";
            return false;
        }
        if (!$this->isDealerUser($data['user_id']) || !$this->isDealerUser($dealer_id)) {
            $this->error = "转移或者被转移者不是分销商用户";
            return false;
        }
        //查询用户下的所有关系
        $refereeLists = RefereeModel::where('dealer_id', '=', $dealer_id)->select()->toArray();
        if (!$refereeLists) {
            // 删除离职员工
            $this->setLeave($dealer_id);
            return true;
        }
        //去除重复的数据
        foreach ($refereeLists as $key => $value) {
            if ($refereeLists[$key]['user_id'] == $data['user_id']) {
                unset($refereeLists[$key]);
            } else {
                $refereeLists[$key]['dealer_id'] = $data['user_id'];
                unset($refereeLists[$key]['create_time']);
                unset($refereeLists[$key]['update_time']);
            }
        }
        // 更新记录
        $this->startTrans();
        try {
            //更新记录
            $refereeLists && (new RefereeModel)->saveAll($refereeLists);
            //更新用户分销人数
            $dealerUser = self::detail($data['user_id']);
            $dealerUser && $dealerUser->save([
                'first_num' => RefereeModel::getRefereeUserCount($data['user_id']),
                'second_num' => RefereeModel::getRefereeUserCount($data['user_id'], 2),
                'third_num' => RefereeModel::getRefereeUserCount($data['user_id'], 3)
            ]);
            // 删除离职员工
            $this->setLeave($dealer_id);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }

    }

}